package site.security;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class HMacUtil {

    private static final String macKey = "uHQwkuivIh7eg21t44KP+jm+mm3uoVoGUDaYUr2PSHG+MLE9KTmuE3o+NVvTtvkRhTI/JiGkW8la8SgC0GkyfQ==";

    public static final String KEY_MAC = "HmacMD5";

    public static String hmac(String pwd) {
        // 变成hmac
        Mac mac = getMac(macKey);
        byte[] ret = mac.doFinal(getUTF8Bytes(pwd));
        String hmac = DatatypeConverter.printBase64Binary(ret);
        return hmac;
    }

    private static Mac getMac(String hmackKey) {
        try {
            SecretKey secretKey = new SecretKeySpec(DatatypeConverter.parseBase64Binary(hmackKey), KEY_MAC);

            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            return mac;
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        } catch (InvalidKeyException ex) {
            throw new RuntimeException(ex);
        }
    }

    private static byte[] getUTF8Bytes(String str) {
        try {
            return str.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String pwd = HMacUtil.hmac("1");
        System.out.println(pwd);
    }
}
